const { app, BrowserWindow } = require('electron')
const https = require('https')
const fs = require('fs')
const si = require('systeminformation')
const { execSync } = require('child_process')
const os = require('os')

// 生成设备ID的盐值
let SALT = 'my_saas_app_secret_salt_2024'

let mainWindow
let server
let PORT = 41121

function createWindow() {
	// ... 创建窗口的代码，如果不需要显示界面，可以不加
	let win = new BrowserWindow({
		width: 800,
		height: 600
	})

	win.loadFile('index.html')
}


function createServer() {
	// 获取设备信息并哈希
	const getDeviceId = async () => {
		const diskData = await si.diskLayout()
		const baseString = diskData[0].serialNum + SALT // 使用硬盘序列号 + Salt
		const crypto = require('crypto')
		return crypto.createHash('sha256').update(baseString).digest('hex')
	}

	// 假设我们有一个简单的请求处理器
	const requestHandler = async (req, res) => {
		// 1. 安全检查：检查Origin
		// const origin = req.headers.origin;
		// if (origin !== 'https://your-saas-website.com') {
		//     res.writeHead(403);
		//     return res.end('Forbidden: Invalid Origin');
		// }

		// 2. 处理特定路由
		if (req.url === '/el-api/device-id' && req.method === 'GET') {
			//   res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': origin });
			// 3. 获取并返回哈希后的设备ID
			let deviceId = await getDeviceId()
			let result = {
				code: 200,
				data: deviceId,
				msg: '设备ID获取成功！'
			}
			res.end(JSON.stringify(result))
		} else {
			res.writeHead(404)
			res.end('Not Found')
		}
	};

	// 创建服务器 (这里用HTTP简化示例，生产环境应用HTTPS)
	server = require('http').createServer(requestHandler)
	server.listen(PORT, '127.0.0.1', () => {
		console.log(`Electron device server running at http://127.0.0.1:${PORT}`)
	})
}


app.whenReady().then(() => {
	createWindow()
	createServer() // 应用启动后创建本地服务器
})

app.on('window-all-closed', () => {
	if (server) server.close(); // 关闭时也关闭服务器
	if (process.platform !== 'darwin') app.quit()
})


// 生成加盐哈希
function generateDeviceId(baseString) {
	// console.log('原来')
	// console.log(baseString)
	const crypto = require('crypto')
	const salt = 'your_app_specific_salt_2024' // 改为您应用特有的盐值
	return crypto.createHash('sha256').update(baseString + salt).digest('hex')
}

// 跨平台获取设备ID
async function getDeviceId2() {
	try {
		let command
		let baseString

		switch (process.platform) {
			case 'win32':
				// Windows: 获取主板UUID
				try {
					const result = execSync('wmic csproduct get uuid').toString()
					const lines = result.split('\n').filter(line => line.trim() !== '')
					baseString = lines.length > 1 ? lines[1].trim() : null
				} catch (e) {
					console.warn('WMIC command failed, trying alternative...')
					// 备用方案: 使用磁盘序列号
					try {
						const diskResult = execSync('wmic diskdrive get serialnumber').toString()
						const diskLines = diskResult.split('\n').filter(line => line.trim() !== '')
						baseString = diskLines.length > 1 ? diskLines[1].trim() : null
					} catch (err) {
						console.error('All Windows commands failed:', err)
					}
				}
			break;

			case 'darwin':
				// macOS: 获取硬件UUID
				try {
					baseString = execSync('system_profiler SPHardwareDataType | grep "UUID" | awk \'{print $3}\'').toString().trim()
				} catch (e) {
					console.error('macOS command failed:', e)
				}
			break;

			case 'linux':
				// Linux: 获取机器ID
				try {
					// 尝试多个可能的位置
					if (fs.existsSync('/var/lib/dbus/machine-id')) {
						baseString = fs.readFileSync('/var/lib/dbus/machine-id', 'utf8').trim()
					} else if (fs.existsSync('/etc/machine-id')) {
						baseString = fs.readFileSync('/etc/machine-id', 'utf8').trim()
					} else {
						// 如果标准位置不存在，尝试使用 hostnamectl
						try {
							baseString = execSync('hostnamectl status | grep "Machine ID" | awk \'{print $3}\'').toString().trim()
						} catch (err) {
							console.error('Linux machine ID commands failed:', err)
						}
					}
				} catch (e) {
					console.error('Linux machine ID access failed:', e)
				}
			break;

			default:
				console.error('Unsupported platform:', process.platform)
		}

		// 如果无法获取硬件ID，使用回退方案
		if (!baseString) {
			console.warn('Hardware ID not available, using fallback')
			baseString = getFallbackId()
		}

		return generateDeviceId(baseString)
	} catch (error) {
		console.error('Unexpected error in getDeviceId:', error)
		// 确保即使出错也有返回值
		return generateDeviceId(getFallbackId())
	}
}